package com.koron.common.core.business.todoApproval.templates;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.business.todoApproval.bean.properties.TodoApprovalProperties;
import com.koron.common.core.config.ThreadLocalContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * OA待办
 * @author jzp
 * @since 2022/10/10
 */
@Slf4j
@Component
@ConditionalOnProperty(name = "oa.ekp.platform", havingValue = "gdhwater", matchIfMissing = true)
public class GdhWaterTodoApprovalModel implements TodoApprovalModel {
    @Autowired
    private TodoApprovalProperties todoApprovalProperties;

    private final String SEND_TODO_URL = "/sendTodo";
    private final String SET_TODO_DONE_URL = "/setTodoDone";
    private final String DELETE_TODO_URL = "/deleteTodo";
    private final String GET_TODO_URL = "/getTodo";

    /**
     * 发起待办
     */
    @Override
    public String startTodo(String bizId, String title, String link, String mobileLink, List<String> accounts, String createBy, Date date, String modelName) {
        return sendTodo(bizId, title, link, mobileLink, accounts, createBy, date, modelName);
    }

    /**
     * 发送待办
     *
     * @param bizId    业务id
     * @param title    业务标题
     * @param link     链接
     * @param accounts 处理人
     * @param createBy 创建人
     * @param date     创建时间
     * @return 处理结果
     */
    @Override
    public String sendTodo(String bizId, String title, String link, String mobileLink, List<String> accounts, String createBy, Date date, String modelName) {
        Assert.notEmpty(accounts, "待审用户不能为空");
        Map<String, Object> paramBody = new HashMap<>();
        paramBody.put("appName", getAppName(modelName));
        paramBody.put("modelName", modelName);
        paramBody.put("modelId", bizId);
        paramBody.put("subject", title);
        paramBody.put("link", link);
        paramBody.put("mobileLink", mobileLink);
        paramBody.put("padLink", mobileLink);
        paramBody.put("type", 1);
        List<HashMap<String, String>> targetsList = accounts.stream().map(e -> {
            HashMap<String, String> map = new HashMap<>();
            map.put("LoginName", e);
            return map;
        }).collect(Collectors.toList());
        paramBody.put("targets", JSONUtil.toJsonStr(targetsList));
        paramBody.put("docCreator", "{\"LoginName\":\"" + createBy + "\"}");
        paramBody.put("createTime", DateUtil.format(date, "yyyy-MM-dd HH:mm:ss"));
        String paramStr = JSONUtil.toJsonStr(paramBody);
        String res = sendRequest(SEND_TODO_URL, paramStr);
        log.info("发送待办，参数：{}，响应：{}", paramStr, res);
        return res;
    }

    /**
     * 删除待办
     *
     * @param bizId 业务id
     * @return 处理结果
     */
    @Override
    public String deleteTodo(String bizId, String modelName) {
        Map<String, Object> paramBody = new HashMap<>();
        paramBody.put("appName", getAppName(modelName));
        paramBody.put("modelName", modelName);
        paramBody.put("modelId", bizId);
        paramBody.put("optType", 1);
        String paramStr = JSONUtil.toJsonStr(paramBody);
        String res = sendRequest(DELETE_TODO_URL, paramStr);
        log.info("删除待办，参数：{}，响应：{}", paramStr, res);
        return res;
    }

    /**
     * 删除指定待办所属人操作 (不会真正删除待办，对待办所属人做已办处理)
     *
     * @param bizId    业务id
     * @param accounts 待办所属人
     * @return 处理结果
     */
    @Override
    public String deleteTodo(String bizId, List<String> accounts, String modelName) {
        Map<String, Object> paramBody = new HashMap<>();
        paramBody.put("appName", getAppName(modelName));
        paramBody.put("modelName", modelName);
        paramBody.put("modelId", bizId);
        paramBody.put("optType", 2);
        List<HashMap<String, String>> targetsList = accounts.stream().map(e -> {
            HashMap<String, String> map = new HashMap<>();
            map.put("LoginName", e);
            return map;
        }).collect(Collectors.toList());
        paramBody.put("targets", JSONUtil.toJsonStr(targetsList));
        String paramStr = JSONUtil.toJsonStr(paramBody);
        String res = sendRequest(DELETE_TODO_URL, paramStr);
        log.info("删除待办，参数：{}，响应：{}", paramStr, res);
        return res;
    }

    /**
     * 设待办为已办
     *
     * @param bizId 业务id
     * @return 处理结果
     */
    @Override
    public String setTodoDone(String bizId, List<String> accounts, String modelName) {
        Map<String, Object> paramBody = new HashMap<>();
        paramBody.put("appName", getAppName(modelName));
        paramBody.put("modelName", modelName);
        paramBody.put("modelId", bizId);
        paramBody.put("optType", 1);
        String paramStr = JSONUtil.toJsonStr(paramBody);
        String res = sendRequest(SET_TODO_DONE_URL, paramStr);
        log.info("设待办为已办，参数：{}，响应：{}", paramStr, res);
        return res;
    }

    /**
     * 设置目标待办所属人为已办
     *
     * @param bizId    业务id
     * @param accounts 待办所属人
     * @return 处理结果
     */
    @Override
    public String setAccountsTodoDone(String bizId, List<String> accounts, String modelName) {
        Map<String, Object> paramBody = new HashMap<>();
        paramBody.put("appName", getAppName(modelName));
        paramBody.put("modelName", modelName);
        paramBody.put("modelId", bizId);
        paramBody.put("optType", 2);
        List<HashMap<String, String>> targetsList = accounts.stream().map(e -> {
            HashMap<String, String> map = new HashMap<>();
            map.put("LoginName", e);
            return map;
        }).collect(Collectors.toList());
        paramBody.put("targets", JSONUtil.toJsonStr(targetsList));
        String paramStr = JSONUtil.toJsonStr(paramBody);
        String res = sendRequest(SET_TODO_DONE_URL, paramStr);
        log.info("设待办为已办，参数：{}，响应：{}", paramStr, res);
        return res;
    }

    /**
     * 获取待办已办数据
     *
     * @param accounts  用户
     * @param rowSize
     * @param pageNo
     * @param type      0表示待办 -1表示已办
     * @param subject   标题
     * @param beginTime
     * @param endTime
     * @return 处理结果
     */
    @Override
    public String getTodo(List<String> accounts, String rowSize, String pageNo, Integer type, String subject, String beginTime, String endTime, String modelName) {
        Map<String, Object> paramBody = new HashMap<>();
        List<HashMap<String, String>> targetsList = accounts.stream().map(e -> {
            HashMap<String, String> map = new HashMap<>();
            map.put("LoginName", e);
            return map;
        }).collect(Collectors.toList());
        paramBody.put("targets", JSONUtil.toJsonStr(targetsList));
        paramBody.put("type", type == null ? 0 : type);
        paramBody.put("rowSize", rowSize);
        paramBody.put("pageNo", pageNo);

        List<HashMap<String, String>> otherCond = new ArrayList<>();

        HashMap<String, String> appNameMap = new HashMap<>();
        appNameMap.put("appName", getAppName(modelName));
        otherCond.add(appNameMap);

        HashMap<String, String> modelNameMap = new HashMap<>();
        modelNameMap.put("modelName", modelName);
        otherCond.add(modelNameMap);

        if (StrUtil.isNotEmpty(subject)) {
            HashMap<String, String> subjectMap = new HashMap<>();
            subjectMap.put("subject", subject);
            otherCond.add(subjectMap);
        }

        if (StrUtil.isNotEmpty(beginTime) && StrUtil.isNotEmpty(endTime)) {
            HashMap<String, String> beginTimeMap = new HashMap<>();
            beginTimeMap.put("beginTime", beginTime);
            otherCond.add(beginTimeMap);

            HashMap<String, String> endTimeMap = new HashMap<>();
            endTimeMap.put("endTime", endTime);
            otherCond.add(endTimeMap);
        }

        paramBody.put("otherCond", JSONUtil.toJsonStr(otherCond));

        String paramStr = JSONUtil.toJsonStr(paramBody);
        String res = sendRequest(GET_TODO_URL, paramStr);
        log.info("获取待办，参数：{}，响应：{}", paramStr, res);
        return res;
    }

    /**
     * 获取当前账号的待办数据
     *
     * @param accounts 用户
     * @param modelId  业务id
     * @return 处理结果
     */
    @Override
    public String getAccountTodo(List<String> accounts, String modelId, String modelName) {
        Map<String, Object> paramBody = new HashMap<>();
        List<HashMap<String, String>> targetsList = accounts.stream().map(e -> {
            HashMap<String, String> map = new HashMap<>();
            map.put("LoginName", e);
            return map;
        }).collect(Collectors.toList());
        paramBody.put("targets", JSONUtil.toJsonStr(targetsList));
        paramBody.put("type", 0);

        List<HashMap<String, String>> otherCond = new ArrayList<>();

        HashMap<String, String> appNameMap = new HashMap<>();
        appNameMap.put("appName", getAppName(modelName));
        otherCond.add(appNameMap);

        HashMap<String, String> modelNameMap = new HashMap<>();
        modelNameMap.put("modelName", modelName);
        otherCond.add(modelNameMap);

        HashMap<String, String> modelIdMap = new HashMap<>();
        modelIdMap.put("modelId", modelId);
        otherCond.add(modelIdMap);

        paramBody.put("otherCond", JSONUtil.toJsonStr(otherCond));

        String paramStr = JSONUtil.toJsonStr(paramBody);
        String res = sendRequest(GET_TODO_URL, paramStr);
        log.info("获取待办，参数：{}，响应：{}", paramStr, res);
        return res;
    }


    private String getAppName(String modelName) {
        // @TODO 2023-08-23 用于后续待办根据流程创建时间判断，参考GdhWaterTodoApprovalModel.getCompatibilityAppName
        return getCompatibilityAppName(modelName);
    }

    private String getCompatibilityAppName(String modelName) {
        // @TODO 2023-08-23 用于后续待办根据流程创建时间判断，参考GdhWaterTodoApprovalModel.getCompatibilityAppName
        EamUser eamUser = ThreadLocalContext.get();
        Date createTime = eamUser.getCreateTime();

        // @TODO 2023-08-28 23到28号的待办有-，输电风控的叫输电风控，其他的不变
        if (DateUtil.isIn(createTime, DateUtil.parseDate("2023-08-23"), DateUtil.parseDate("2023-08-29"))) {
            return todoApprovalProperties.getAppName() + "-" + modelName;
        }
        if ("输电风控".equals(modelName)) {
            return "输电风控";
        }

        return todoApprovalProperties.getAppName();
    }

    @Override
    public String getAuthorization() {
        String yourEncryptedWorlds = getEncryptedWorlds();
        String encodedAuth = Base64.encode(yourEncryptedWorlds.getBytes(StandardCharsets.UTF_8));
        return "Basic " + encodedAuth;
    }

    public String getEncryptedWorlds() {
        return todoApprovalProperties.getAccountID() + ":" + todoApprovalProperties.getAccountPassword();
    }

    @Override
    public String getRequestUrl(String suffixUrl) {
        return todoApprovalProperties.getServer() + suffixUrl;
    }
}
